//
//  LoginViewController.m
//  Grammar
//
//  Created by Rick on 7/6/13.
//
//

#import "LoginViewController.h"
#import "AppDelegate.h"
#import "ThirdLoginDataRequest.h"
#import "SinaWeibo.h"
#import "SinaWeiboRequest.h"

typedef enum{
    LoginTypeTableViewNotLogin = 1,
    LoginTypeTableViewLogined,
}LoginTypeTableView;

@interface LoginViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate,SinaWeiboDelegate, SinaWeiboRequestDelegate>
{
    NSMutableArray* _permissions;
    LoginTypeTableView _type;
    NSMutableString *nickString;
}
@property (retain, nonatomic) IBOutlet UIView *footView;
@property (retain, nonatomic) IBOutlet UITableView *loginTableView;
@end

@implementation LoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (SinaWeibo *)sinaweibo
{
    return [AppDelegate shareAppdelegate].sinaweibo;
}

- (void)removeAuthData
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"SinaWeiboAuthData"];
}

- (void)storeAuthData
{
    SinaWeibo *sinaweibo = [self sinaweibo];
    
    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
                              sinaweibo.accessToken, @"AccessTokenKey",
                              sinaweibo.expirationDate, @"ExpirationDateKey",
                              sinaweibo.userID, @"UserIDKey",
                              sinaweibo.refreshToken, @"refresh_token", nil];
    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"SinaWeiboAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    nickString = [[NSMutableString alloc] init];
    // Do any additional setup after loading the view from its nib.
    _permissions = [[NSArray arrayWithObjects:
                     kOPEN_PERMISSION_GET_USER_INFO,
                     kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
                     kOPEN_PERMISSION_ADD_ALBUM,
                     kOPEN_PERMISSION_ADD_IDOL,
                     kOPEN_PERMISSION_ADD_ONE_BLOG,
                     kOPEN_PERMISSION_ADD_PIC_T,
                     kOPEN_PERMISSION_ADD_SHARE,
                     kOPEN_PERMISSION_ADD_TOPIC,
                     kOPEN_PERMISSION_CHECK_PAGE_FANS,
                     kOPEN_PERMISSION_DEL_IDOL,
                     kOPEN_PERMISSION_DEL_T,
                     kOPEN_PERMISSION_GET_FANSLIST,
                     kOPEN_PERMISSION_GET_IDOLLIST,
                     kOPEN_PERMISSION_GET_INFO,
                     kOPEN_PERMISSION_GET_OTHER_INFO,
                     kOPEN_PERMISSION_GET_REPOST_LIST,
                     kOPEN_PERMISSION_LIST_ALBUM,
                     kOPEN_PERMISSION_UPLOAD_PIC,
                     kOPEN_PERMISSION_GET_VIP_INFO,
                     kOPEN_PERMISSION_GET_VIP_RICH_INFO,
                     kOPEN_PERMISSION_GET_INTIMATE_FRIENDS_WEIBO,
                     kOPEN_PERMISSION_MATCH_NICK_TIPS_WEIBO,
                     nil] retain];
    
    NSString *uid = (NSString*)[[DataCacheManager sharedManager] getCachedObjectByKey:KEY_USER_ID];
    if (uid && uid.length > 0) {
        _type = LoginTypeTableViewLogined;
        _loginTableView.tableFooterView = _footView;
    }else {
        _type = LoginTypeTableViewNotLogin;
    }
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"THIRD_LOGIN_DATA_REQUEST" object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)tapQQLoginButton:(id)sender {
    
}
- (IBAction)tapSinaButton:(id)sender {

    
}

- (IBAction)tapBackButton:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidUnload
{
    [self setFootView:nil];
    [self setLoginTableView:nil];
    [super viewDidUnload];
}

- (void)dealloc
{
    [nickString release];
    [_footView release];
    [_permissions release];
    [_loginTableView release];
    [super dealloc];
}


/**
 * 登录成功后的回调
 */
- (void)tencentDidLogin
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"QQ登录成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alertView show];
    [alertView release];
    
    _type = LoginTypeTableViewLogined;
    
    
    
    ITTDINFO(@"login qq sucess ,openId = %@",[AppDelegate shareAppdelegate].tencentOAuth.openId);
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"qq" forKey:@"provider"];
    [parameters setObject:[AppDelegate shareAppdelegate].tencentOAuth.openId forKey:@"uid"];
    [[AppDelegate shareAppdelegate].tencentOAuth getUserInfo];
    
    [ThirdLoginDataRequest requestWithParameters:parameters withIndicatorView:self.view withCancelSubject:@"THIRD_LOGIN_DATA_REQUEST" onRequestStart:nil onRequestFinished:^(ITTBaseDataRequest *request) {
        
    } onRequestCanceled:^(ITTBaseDataRequest *request) {
        
    } onRequestFailed:^(ITTBaseDataRequest *request) {
        
    }];
    
}

/**
 * 获取用户个人信息回调
 */
/**
 * Called when the get_user_info has response.
 */
- (void)getUserInfoResponse:(APIResponse*) response {
	if (response.retCode == URLREQUEST_SUCCEED)
	{
		
        _loginTableView.tableFooterView = _footView;
        [nickString setString:[NSString stringWithFormat:@"QQ登录:%@",[response.jsonResponse objectForKey:@"nickname"]]];
        [[DataCacheManager sharedManager] addObject:nickString forKey:@"LOGIN_NAME"];
        [_loginTableView reloadData];
//		for (id key in response.jsonResponse) {
//			[str appendString: [NSString stringWithFormat:@"%@:%@\n",key,[response.jsonResponse objectForKey:key]]];
//		}
//		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"操作成功" message:[NSString stringWithFormat:@"%@",str]
//							  
//													   delegate:self cancelButtonTitle:@"我知道啦" otherButtonTitles: nil];
//		[alert show];
//        [alert release];
	}
	else
    {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"操作失败" message:[NSString stringWithFormat:@"%@", response.errorMsg]
							  
													   delegate:self cancelButtonTitle:@"我知道啦" otherButtonTitles: nil];
		[alert show];
        [alert release];
	}
}

/**
 * 登录失败后的回调
 * \param cancelled 代表用户是否主动退出登录
 */
- (void)tencentDidNotLogin:(BOOL)cancelled
{
    ITTDINFO(@"login qq cancle");
}

/**
 * 登录时网络有问题的回调
 */
- (void)tencentDidNotNetWork
{
    ITTDINFO(@"login qq not net word");
}

#pragma mark - SinaWeibo Delegate

- (void)sinaweiboDidLogIn:(SinaWeibo *)sinaweibo
{
//    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"新浪微博登录成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
//    [alertView show];
//    [alertView release];
    
    _type = LoginTypeTableViewLogined;
    [self storeAuthData];
    
    SinaWeibo *sinaweiboRequest = [self sinaweibo];
    [sinaweiboRequest requestWithURL:@"users/show.json"
                       params:[NSMutableDictionary dictionaryWithObject:sinaweibo.userID forKey:@"uid"]
                   httpMethod:@"GET"
                     delegate:self];
    
    
    
    ITTDINFO(@"sinaweiboDidLogIn userID = %@ accesstoken = %@ expirationDate = %@ refresh_token = %@", sinaweibo.userID, sinaweibo.accessToken, sinaweibo.expirationDate,sinaweibo.refreshToken);
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"sina" forKey:@"provider"];
    [parameters setObject:sinaweibo.userID forKey:@"uid"];
    
    [ThirdLoginDataRequest requestWithParameters:parameters withIndicatorView:self.view withCancelSubject:@"THIRD_LOGIN_DATA_REQUEST" onRequestStart:nil onRequestFinished:^(ITTBaseDataRequest *request) {
        
    } onRequestCanceled:^(ITTBaseDataRequest *request) {
        
    } onRequestFailed:^(ITTBaseDataRequest *request) {
        
    }];
    
    
}
- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result
{
    if ([request.url hasSuffix:@"users/show.json"])
    {
        _loginTableView.tableFooterView = _footView;
        [nickString setString:[NSString stringWithFormat:@"新浪微博登录:%@",[result objectForKey:@"name"]]];
        [[DataCacheManager sharedManager] addObject:nickString forKey:@"LOGIN_NAME"];
        [_loginTableView reloadData];
//        [userInfo release];
//        userInfo = [result retain];
    }
}
- (void)sinaweiboDidLogOut:(SinaWeibo *)sinaweibo
{
    ITTDINFO(@"sinaweiboDidLogOut");
    [self removeAuthData];
}

- (void)sinaweiboLogInDidCancel:(SinaWeibo *)sinaweibo
{
    ITTDINFO(@"sinaweiboLogInDidCancel");
}

- (void)sinaweibo:(SinaWeibo *)sinaweibo logInDidFailWithError:(NSError *)error
{
    ITTDINFO(@"sinaweibo logInDidFailWithError %@", error);
}

- (void)sinaweibo:(SinaWeibo *)sinaweibo accessTokenInvalidOrExpired:(NSError *)error
{
    ITTDINFO(@"sinaweiboAccessTokenInvalidOrExpired %@", error);
    [self removeAuthData];
}

#pragma mark - UITableView
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (_type) {
        case LoginTypeTableViewNotLogin:
        {
            return 2;
        }
            break;
        case LoginTypeTableViewLogined:
        {
            return 1;
        }
            break;
        default:
            return 1;
            break;
    }
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 1;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    NSString *cellIdentifier = @"cellIdentifier";
    UILabel *label = nil;
    UITableViewCell *cell =nil;
    if (!cell) {
        
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
        label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 300, 34)];
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor = [UIColor clearColor];
        [cell addSubview:label];
    }
    
    
    switch (_type) {
        case LoginTypeTableViewNotLogin:
        {
            if (indexPath.row == 0) {
                label.text = @"QQ登录";
            }else if (indexPath.row == 1) {
                label.text = @"新浪微博登录";
            }
        }
            break;
        case LoginTypeTableViewLogined:
        {
            if (indexPath.row == 0) {
                label.text = [NSString stringWithFormat:@"%@",[[DataCacheManager sharedManager] getCachedObjectByKey:@"LOGIN_NAME"]];
            }
            
        }
            break;
        default:
            break;
    }
    [label release];
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (_type) {
        case LoginTypeTableViewLogined:
            
            break;
        case LoginTypeTableViewNotLogin:
        {
            if (indexPath.row == 0) {
                //QQ直联
                DATA_ENV.isQQConnect = YES;
                TencentOAuth *tencentOAuth = [AppDelegate shareAppdelegate].tencentOAuth;
                tencentOAuth.sessionDelegate = self;
                [tencentOAuth authorize:_permissions inSafari:NO];
            }else {
                //新浪微博直联
                DATA_ENV.isQQConnect = NO;
                SinaWeibo *sinaweibo = [self sinaweibo];
                sinaweibo.delegate = self;
                [sinaweibo logIn];
            }
        }
            break;
        default:
            break;
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (IBAction)tapLoginOutButton:(id)sender {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"确定是否退出登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alertView show];
    [alertView release];
}

#pragma mark - UIAlertView
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
            //cancle
            break;
        case 1:
            //confirm
            if (DATA_ENV.isQQConnect) {
                [AppDelegate shareAppdelegate].tencentOAuth.sessionDelegate = self;
                [[AppDelegate shareAppdelegate].tencentOAuth logout:self];
            }else {
                [AppDelegate shareAppdelegate].sinaweibo.delegate = self;
                [[AppDelegate shareAppdelegate].sinaweibo logOut];
            }
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"退出登录成功" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles: nil];
            [alert show];
            [alert release];
            [self.navigationController popViewControllerAnimated:YES];
            [[DataCacheManager sharedManager] removeObjectInCacheByKey:KEY_USER_ID];
            break;
        default:
            break;
    }
}
@end
